import React from "react"
import classes from './Auth.css'
import Button from '../../components/UI/Button/Button'
import Input from '../../components/UI/Input/Input'
import is from 'is_js'
import axios from "axios"


export default class Auth extends React.Component {

    state = {
        isFormValid: false,
        formControls : {
            email: {
                value : "",
                type : 'email',
                label : 'Email',
                errorMessage : 'Введите корректный email',
                valid: false,
                touched:false,
                validation: {
                    required: true,
                    email: true
                }
            },
            password: {
                value : "",
                type : 'password',
                label : 'Пароль',
                errorMessage : 'Введите корректный password',
                valid: false,
                touched:false,
                validation: {
                    required: true,
                    minLength: 6
                }
            }
        }
    }

    loginHandler = async () => {
        const authData = {
            email: this.state.formControls.email.value,
            password: this.state.formControls.password.value,
            returnSecureToken: true
        }
        
        try{
            const response = await axios.post('https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyDrpGXMI-JFeET_w0pK18P-q2hv5ppua_Q', authData)

            console.log(response.data)
        } catch(e) {
            console.log(e)
        }
    }

    registrHandler = async () => {
        const authData = {
            email: this.state.formControls.email.value,
            password: this.state.formControls.password.value,
            returnSecureToken: true
        }
        
        try{
            const response = await axios.post('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=AIzaSyDrpGXMI-JFeET_w0pK18P-q2hv5ppua_Q', authData)

            console.log(response.data)
        } catch(e) {
            console.log(e)
        }
    }

    submitHandler = event => {
        event.preventDefault()
    }

    validateControl (value, validation) {
        if (!validation) {
            return true
        }
        let isValid = true
        

        if (validation.required) {
            isValid  = value.trim() !== '' && isValid
        }

        if (validation.email) {
            isValid = is.email(value) && isValid
        }

        if (validation.minLength) {
            isValid = value.length >=  validation.minLength && isValid
        }

        return isValid
    }


    onChangeHandler = (event, controlName) => {
        //console.log(`${controlName}: `, event.target.value)

        const formControls = { ...this.state.formControls}
        const control = {...formControls[controlName]}

        control.value = event.target.value
        control.touched =  true
        control.valid = this.validateControl(control.value, control.validation)
        
        let isFormValid = true

        Object.keys(formControls).forEach(name => {
            isFormValid = formControls[name].valid && isFormValid
        })

        formControls[controlName] = control
        this.setState({
            formControls, isFormValid
        })
    }

    renderInputs () {
        const inputs = Object.keys(this.state.formControls).map((controlName, index) => {
            const control = this.state.formControls[controlName]

            return (

                <Input 
                key={controlName + index}
                type={control.type}
                label={control.label}
                value={control.value}
                valid={control.valid}
                touched={control.touched}
                shouldValidate={!!control.validation}
                errorMessage={control.errorMessage}
                onChange={event => this.onChangeHandler(event, controlName)}
                />
            
            )
        })

        return inputs
    }

    render () {

        return (
            <div className={classes.Auth}>
                <div>
                    <h1>Авторизация</h1>

                    <form onSubmit={this.submitHandler} className={classes.AuthForm}>

                        { this.renderInputs() }

                        <Button 
                        type='success' 
                        onClick={this.loginHandler}
                        disabled = {!this.state.isFormValid}
                        >
                            Войти
                        </Button>

                        <Button 
                        type='primary' 
                        onClick={this.registrHandler}
                        disabled = {!this.state.isFormValid}
                        >
                            Регистрация
                        </Button>
                    </form>
                </div>
            </div>
        )
    }
}